package com.rd.student.ruanjian.class4.zhangrui;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantLock;

public class TestBank implements Runnable {

    private Account account;
    private double money;
    private ReentrantLock lock;

    public TestBank(Account account, double money) {
        this.account = account;
        this.money = money;
        this.lock = new ReentrantLock();
    }

    @Override
    public void run() {
        lock.lock(); // 加锁
        try {
            if (account.balance < money) {
                System.out.println("余额不足");
                return;
            }

            System.out.println(Thread.currentThread().getName() + " 可以取钱");
            account.balance = account.balance - money;
            System.out.println("取钱后的余额为：" + account.balance);
        } finally {
            lock.unlock(); // 解锁
        }
    }

    public static void main(String[] args) {
        Account account = new Account("123456", 888);
        TestBank testBank = new TestBank(account, 666);
        Thread t1 = new Thread(testBank, "zhangsan");
        Thread t2 = new Thread(testBank, "lisi");

        t1.start();
        t2.start();
    }
}

class Account {
    String accountId;
    double balance;

    public Account(String accountId, double balance) {
        this.accountId = accountId;
        this.balance = balance;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Account account = (Account) o;
        return Objects.equals(accountId, account.accountId);
    }

    @Override
    public int hashCode() {
        return Objects.hash(accountId);
    }
}